package com.haohan.schedule;

/**
 * @author: jzhou
 * @date: 2024/12/22-15:46
 * @version: 1.0
 * @description: compass
 */
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;

import java.io.*;

@Slf4j
public class RemoteServerChecker {

    public static void main(String[] args) {
        String remoteHost = "10.10.4.41";
        String user = "root";
        String password = "tma@1100";
        int port = 22; // SSH 默认端口

        Session session = null;
        ChannelExec channelExec = null;

        if (!isReachable(remoteHost)) {
            return;
        }

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(user, remoteHost, port);
            session.setPassword(password);

            // 禁用主机密钥检查，这在生产环境中是不推荐的，应该使用更安全的方法处理主机密钥
            session.setConfig("StrictHostKeyChecking", "no");

            session.connect(1000);

            System.out.println("Connected to " + remoteHost);

            channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand("uptime -p");

            InputStream in = channelExec.getInputStream();
            channelExec.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("up")) {
                    // 提取开机时间
                    String uptime = line.split("up ")[1].replaceAll(",","");
                    System.out.println("Server is up and running for: " + uptime);
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Failed to connect to " + remoteHost + " or execute command.");
        } finally {
            if (channelExec != null && channelExec.isConnected()) {
                channelExec.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }

    private static boolean isReachable(String host) {
        CommandLine commandLine = new CommandLine("ping");
        commandLine.addArgument(host);
        // 判断操作系统
        if (System.getProperty("os.name").toLowerCase().contains("win")) {
            commandLine.addArgument("-n").addArgument("1"); // For Windows
        } else {
            commandLine.addArgument("-c").addArgument("1"); // For Linux/Mac
        }

        Executor executor = new DefaultExecutor();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream,null);
        executor.setExitValues(null); // Accept all exit values
        executor.setStreamHandler(streamHandler);

        try {
            int exitCode = executor.execute(commandLine);
            String output = outputStream.toString("GBK");
//            log.info("Ping output: {}", output);
            log.info("Ping exit code: {}", exitCode);
            return exitCode == 0;
        } catch (ExecuteException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
/*        try {
            String os = System.getProperty("os.name").toLowerCase();
            String pingCommand = os.contains("win") ? "ping -n 1 " : "ping -c 1 ";
            Process process = Runtime.getRuntime().exec(pingCommand + host);
            int exitCode = process.waitFor();
            return exitCode == 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }*/
    }
}
